package com.gwtgeo.service.manager.impl;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

import com.gwtgeo.service.exception.GwtgeoException;
import com.gwtgeo.service.manager.BaseLayersManager;
import com.gwtgeo.service.model.WMSLayerDef;

public class BaseLayersManagerImpl implements BaseLayersManager{

	private Unmarshaller unmarshaller;
	
	private Marshaller marshaller;
	
	private String configFile;
	
	@SuppressWarnings("unchecked")
	public List<WMSLayerDef> getAll() throws GwtgeoException{
		
		FileInputStream is = null;
		try {
			try {
				is = new FileInputStream(configFile);
				return (List<WMSLayerDef>) this.unmarshaller.unmarshal(new StreamSource(is));
			} finally {
				if (is != null) {
					is.close();
				}
			}
		} catch (Exception e) {
			throw new GwtgeoException(e);
		}
	}
	
	public void define(List<WMSLayerDef> defs) throws GwtgeoException {
		FileOutputStream os = null;
		try {
			try {
				os = new FileOutputStream(configFile);
				this.marshaller.marshal(defs, new StreamResult(os));
			} finally {
				if (os != null) {
					os.close();
				}
			}
		} catch (Exception e) {
			throw new GwtgeoException(e);
		}
	}

	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}

	public void setConfigFile(String configFile) {
		this.configFile = configFile;
	}

	public void setMarshaller(Marshaller marshaller) {
		this.marshaller = marshaller;
	}	
}
